package com.xuecheng.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.xuecheng.order.utils.PayUtils;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 订单支付信息 服务实现类
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayUtils payUtils;

    /**
     * 创建支付信息，获取微信支付的二维码
     *  1、只能对已下单，未支付的订单创建支付信息
     *  2、支付信息只能存在一次
     */
    public ResponseResult<String> createPay(String orderNo) {
        //1、查询订单，判断订单状态
        LambdaQueryWrapper<Orders> orderQw = new LambdaQueryWrapper<>();
        orderQw.eq(Orders::getOrderNo,orderNo);
        Orders orders = ordersService.getOne(orderQw);
        if(!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        //2、查询支付信息，判断是否存在支付数据
        LambdaQueryWrapper<Payment> payQw = new LambdaQueryWrapper<>();
        payQw.eq(Payment::getOrderNo,orderNo);
        Payment payment = this.getOne(payQw);
        //3、构造支付数据，存入到数据库中
        if(payment == null) {
            payment = new Payment();
            payment.setUserId(AuthInfoHolder.getUserId());
            payment.setOrderNo(orderNo);
            payment.setCompanyId(orders.getCompanyId());
            payment.setTotalAmount(orders.getPrice());
            payment.setCreateDate(new Date());
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX);//支付方式
            payment.setStatus(OrdersConstants.NOT_PAID.toString());
            boolean save = this.save(payment);
            if (!save) {
                throw new BusinessException(ErrorCode.ERROR);
            }
        }
        //4、调用微信工具类，生成支付二维码
        String url = payUtils.createOrder(payment.getOrderNo(),
                payment.getTotalAmount(),
                orders.getCoursePubName());
        //5、返回
        return ResponseResult.okResult(url);
    }
}
